<template>
  <div class="execution">
    <basic-container>
      <div style="display: flex;align-items: center;justify-content: space-between">
        <div style="display: flex">
          <div style="display: flex;align-content: center;align-items: center">
            <div style="white-space: nowrap">标签名称：</div>
            <el-input size="small" v-model="searchLabelName" placeholde="请输入标签名称"></el-input>
          </div>
          <div style="display: flex;align-content: center;align-items: center;margin-left: 20px">
            <div style="white-space: nowrap">类型名称：</div>
            <avue-crud-select
              v-model="checkedType"
              size="small"
              placeholder="请选择类型"
              :dic="typeOptions"
              :props="typeProps"
            ></avue-crud-select>
          </div>
          <div
            style="display: flex;align-content: center;align-items: center;margin-left: 20px"
            v-if="isShowShop"
          >
            <div style="white-space: nowrap">商铺名称：</div>
            <avue-crud-select
              v-model="searchShopId"
              size="small"
              placeholder="请选择商铺"
              :dic="shopsOptions"
              :props="shopsProps"
            ></avue-crud-select>
          </div>
          <el-button
            style="margin-left: 30px"
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="searchChange"
          >搜索</el-button>
          <el-button style="margin-left: 10px" size="small" icon="el-icon-delete">清空</el-button>
        </div>
      </div>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        v-model="form"
        @current-change="currentChange"
        @size-change="sizeChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="menuLeft">
          <el-button type="primary" @click="handleAdd" size="small">新 增</el-button>
          <br />
          <br />
        </template>
        <template slot="merSerTypeId" slot-scope="scope">
          <div>{{scope.row.merSerTypeName}}</div>
        </template>
        <template slot="shopName" slot-scope="scope">
          <div>{{scope.row.shopName}}</div>
        </template>
        <template slot="isRecommend" slot-scope="scope">
          <el-tag v-if="scope.row.isRecommend === 1">已推荐</el-tag>
          <el-tag type="info" v-else>未推荐</el-tag>
        </template>
        <template slot="labelSort" slot-scope="scope">
          <el-input
            v-if="scope.row.sortEdit == true"
            v-model="scope.row.labelSort"
            @blur="submitSort(scope.row.labelSort)"
            @keyup.enter.native="submitSort(scope.row.labelSort)"
          ></el-input>
          <div v-else>
            <span>{{scope.row.labelSort}}</span>
            <el-button type="text" @click="editSort(scope.row)">
              <i class="el-icon-edit"></i>
            </el-button>
          </div>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            icon="el-icon-check"
            size="small"
            plain
            @click="handleEdit(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            size="small"
            plain
            @click="handleDel(scope.row,scope.index)"
          >删除</el-button>
        </template>
        <template slot="shopNameForm" slot-scope="scope">
          <avue-crud-select
            v-model="shopId"
            placeholder="请选择商铺"
            :dic="shopsOptions"
            :props="shopsProps"
          ></avue-crud-select>
        </template>
        <template slot="labelImageForm" slot-scope="scope">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :limit="1"
            :file-list="fileList"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleImageRemove"
          >
            <!--:before-upload="uploadBefore"-->
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
        <template slot="labelIconForm" slot-scope="scope">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :limit="1"
            :file-list="fileLists"
            list-type="picture-card"
            :on-success="handleUploadSucces"
            :on-remove="handleIconRemove"
          >
            <!--:before-upload="uploadBefore"-->
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
        <template slot="merSerTypeIdForm" slot-scope="scope">
          <avue-crud-select
            v-model="form.merSerTypeId"
            placeholder="请选择类型"
            :dic="typeOptions"
            :props="typeProps"
          ></avue-crud-select>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import Vue from "vue";
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  allMerServiceTypes,
  editLabelSort
} from "@/api/merchantservices/label";
import { getListByType } from "@/api/merchantservices/merservicestype";
import { tableOption } from "@/const/crud/merchantservices/label";
import { getShopsByType } from "@/api/shop/shops";
import { getMerTypeByShopId } from "@/api/shop/shopservicestype";
import { handleImgUrl } from "@/utils/util";
export default {
  name: "label",
  data() {
    return {
      headers: {
        token: Vue.cookie.get("token")
      },
      shopsProps: {
        label: "shopName",
        value: "id"
      },
      typeProps: {
        label: "name",
        value: "id"
      },
      shopsOptions: [],
      searchTypeOptions: [],
      isShowShop: false,
      typeOptions: [],
      checkedType: "",
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOption,
      shopId: "",
      typeId: "",
      shopName: "",
      typeName: "",
      searchShopId: "",
      actionUrl: "",
      fileList: [],
      fileLists: [],
      searchLabelName: "",
      form: {
        labelIcon: "",
        labelImage: ""
      },
      editIdx: null
    };
  },
  // computed: {
  //   ...mapGetters(['permissions'])
  // },
  watch: {
    shopName() {
      this.form.shopName = this.shopName;
    }
  },
  mounted() {
    this.actionUrl = this.$http.adornUploadUrl();
    this.searchShopId = this.$store.state.user.shopId;
    if (this.searchShopId) {
      this.isShowShop = false;
    } else {
      this.isShowShop = true;
    }
    this.getSeversType()
    this.getList(this.page, {
      type: this.checkedType,
      shopId: this.searchShopId
    });
  },
  methods: {
    getSeversType() {
      const data = new FormData();
      data.append("types", [1]);
      getListByType(data).then(res => {
        this.typeOptions = res.data.data;
        this.getAllShops()
      });
    },
    getAllShops() {
      const params = new FormData();
      params.append("shopId", this.$store.state.user.shopId);
      params.append("type", 1);
      getShopsByType(params).then(res => {
        this.shopsOptions = res.data.data;
      });
    },
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params
        )
      ).then(response => {
        this.tableData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    /**
     * @title 打开新增窗口
     * @detail 调用crud的handleadd方法即可
     *
     **/
    handleAdd: function() {
      this.getAllShops();
      this.$refs.crud.rowAdd();
      this.form.shopName = this.shopName;
      this.form.merSerTypeId = this.typeOptions[0].id
      this.shopId = this.searchShopId;
      this.fileList = [];
      this.fileLists = [];
    },
    handleEdit(row, index) {
      this.getAllShops();
      this.form.labelImage = row.labelImage;
      this.form.labelIcon = row.labelIcon;
      if (row.labelImage) {
        handleImgUrl(row.labelImage).then(res => {
          this.fileList = [
            {
              url: res.data
            }
          ];
        });
      }
      if (row.labelIcon) {
        handleImgUrl(row.labelIcon).then(res => {
          this.fileLists = [
            {
              url: res.data
            }
          ];
        });
      }
      this.$refs.crud.rowEdit(row, index);
      this.shopId = row.shopId;
    },
    handleDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    rowDel: function(row, index) {
      var _this = this;
      this.$confirm("是否确认删除ID为" + row.labelId, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.labelId);
        })
        .then(data => {
          _this.tableData.splice(index, 1);
          _this.$message({
            showClose: true,
            message: "删除成功",
            type: "success"
          });
          this.getList(this.page, {
            type: this.checkedType,
            shopId: this.searchShopId
          });
        })
        .catch(function(err) {});
    },
    handleUploadSuccess(res, file) {
      this.form.labelImage = res.data.bucketName + "-" + res.data.fileName;
    },
    handleUploadSucces(res, file) {
      this.form.labelIcon = res.data.bucketName + "-" + res.data.fileName;
    },
    handleImageRemove() {
      this.fileList = [];
      this.form.labelImage = "";
    },
    handleIconRemove() {
      this.fileLists = [];
      this.form.labelIcon = "";
    },

    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate: function(row, index, done) {
      this.checkedType = row.type;
      row.shopId = this.shopId;
      row.shopName = this.shopName;
      putObj(row).then(data => {
        this.tableData.splice(index, 1, Object.assign({}, row));
        this.$message({
          showClose: true,
          message: "修改成功",
          type: "success"
        });
        done();
        this.searchShopId = this.shopId;
        this.getList(this.page, {
          type: this.checkedType,
          shopId: this.searchShopId
        });
      });
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave: function(row, done) {
      row.isRecommend = row.isRecommend ? 1 : 0;
      row.type = this.checkedType;
      row.shopId = this.shopId;
      row.shopName = this.shopName;
      addObj(row).then(data => {
        this.tableData.push(Object.assign({}, row));
        this.$message({
          showClose: true,
          message: "添加成功",
          type: "success"
        });
        done();
        this.searchShopId = this.shopId;
        this.getList(this.page, {
          type: this.checkedType,
          shopId: this.searchShopId
        });
      });
    },
    handlerShopsChange(value) {
      for (let i = 0; i < this.shopsOptions.length; i++) {
        if (this.shopsOptions[i].id === value) {
          this.shopName = this.shopsOptions[i].shopName;
        }
      }
      if (value) {
        let data = new FormData();
        data.append("shopId", value);
        getMerTypeByShopId(data).then(res => {
          this.typeOptions = res.data.data;
        });
      }
    },
    searchChange() {
      let params = {};
      params.merSerTypeId = this.checkedType;
      params.shopId = this.searchShopId;
      params.labelName = this.searchLabelName;
      if (params) {
        this.getList(this.page, params);
      }
    },
    currentChange(val) {
      this.page.currentPage = val;
      this.getList(this.page);
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
      this.getList(this.page);
    },
    // 修改标签排序
    editSort(row) {
      if (this.editIdx !== null) {
        this.$set(this.tableData[this.editIdx], "sortEdit", false);
      }
      this.editIdx = row.$index;
      this.$set(row, "sortEdit", true);
    },

    submitSort(sort) {
      if (this.tableData[this.editIdx].sortEdit) {
        let data = new FormData();
        data.append("id", this.tableData[this.editIdx].labelId);
        data.append("sort", sort);
        editLabelSort(data).then(res => {
          if (res.data.code == 0) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.getList(this.page);
          } else {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: "error"
            });
          }
        });
      }
    },
  }
};
</script>

<style lang="scss" scoped>
</style>
